'''
websocket长连接 聊天室案例
'''
# 引入需要的模块
from tornado.web import RequestHandler, Application
from tornado.httpserver import HTTPServer
from tornado.websocket import WebSocketHandler
from tornado.ioloop import IOLoop
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
import multiprocessing
import datetime
import pymysql
import hashlib
import draw
import run
import os
import sys
import re

mysql_settings = {
    "host": "127.0.0.1",
    "user": "root",
    "password": "",
    "db": "webproject",
    "charset": "utf8"
}

chattingRoomList = {"1": {"name": "牛津英语一年级(上)","users":[],"creater":""}, 
"2":{ "name": "综合项目实践","users":[],"creater":""}}

data={}#{用户名:{roomid:[]}}

class BaseHandler(RequestHandler):
    def get_current_user(self):
        return self.get_secure_cookie("nickname")
    
#登录
class Login(BaseHandler):
    def get(self):
        self.render('login.html',w_flag=0)
    def post(self):
        username = self.get_argument('username')
        password = self.get_argument('password')
        db_connect = pymysql.connect(**mysql_settings)
        cursor = db_connect.cursor()
        select_sql = 'select * from mytable where username="{}"'.format(username)
        cursor.execute(select_sql)
        db_connect.close()
        result = cursor.fetchall()

        if result is ():
            # self.write('用户不存在')
            # self.get()
            self.render('login.html',w_flag=1)
        else:
            user_info = result[0]
            if username == user_info[0] and password == user_info[1]:
                self.set_secure_cookie('nickname',username)
                if(username not in data):
                    data[username]={}
                self.redirect('/room')
                # self.write('登陆成功<br><br>用户: {}<br>密码: {}<br>登录地ip: {}'
                #            .format(username, password, self.request.remote_ip))
            else:
                self.render('login.html',w_flag=2)
                # self.write('用户名或密码错误')
                # self.get()

#注册
class Register(BaseHandler):
    def get(self):
        self.render('register.html',w_flag=0)
    def post(self):
        username = self.get_argument('username')
        password = self.get_argument('password')
        sno=self.get_argument('sno')
        if len(username) > 10 or len(username) <= 0 or len(password) <= 0:
            # self.write('注册失败，用户名长度：1~10，密码长度 > 0')
            # self.get()
            self.render('register.html',w_flag=1)
        else:
            db_connect = pymysql.connect(**mysql_settings)
            cursor = db_connect.cursor()
            select_sql = 'select username from mytable where username="{}"'.format(username)
            select_sqp2= 'select sno from mytable where sno="{}"'.format(sno)

            cursor.execute(select_sql)
            name_tup=cursor.fetchall()

            cursor.execute(select_sqp2)
            sno_tup=cursor.fetchall()

            if(len(name_tup)>0):
                
                db_connect.close()
                # self.write('用户已存在，请重新输入')
                # self.get()
                self.render('register.html',w_flag=2)
            elif(len(sno_tup)>0):
                db_connect.close()
                self.render('register.html',w_flag=3)
            else:
                insert_sql = 'insert into mytable values("{}","{}","{}")'.format(username, password,sno)
                cursor.execute(insert_sql)
                db_connect.commit()
                #self.write('注册成功')
                self.render('login.html',w_flag=3)

                db_connect.close()

#聊天室选择页面
class roomchooseHandler(BaseHandler):
    def get(self):
        self.render('chat.html',nickname=self.current_user,chatHomeList=chattingRoomList,w_flag=3)
    def post(self):
        homeDict = {}
        homeDict["name"] = self.get_argument('newname')
        homeDict["users"]=[]
        homeDict["creater"]=str(self.current_user,encoding="utf-8")
        max=0
        for i in chattingRoomList:
            if(int(i)>max):
                max=int(i)
        chattingRoomList[str(max+1)]=homeDict
        nickname=self.current_user
        self.render('chat.html',nickname=self.current_user,chatHomeList=chattingRoomList,w_flag=3)

#删除聊天室功能
class roomdelHandler(BaseHandler):
    def post(self):
        name=str(self.current_user,encoding='utf-8')
        delid=self.get_argument('wasteid')
        
        flag=2 #1成功 2失败 3无
        for i in chattingRoomList:
            if(i==delid and chattingRoomList[i]["creater"]==name):
                del chattingRoomList[i]
                flag=1
                break
        self.render('chat.html',nickname=self.current_user,chatHomeList=chattingRoomList,w_flag=flag)
        
Name=['']
Roomid=['']
Roomname=['']

class roomHandler(BaseHandler):
    def get(self):
        roomid=self.get_argument('pickid')
        roomname=''
        nickname=str(self.current_user,encoding="utf-8")
        user_lst=[1,2,3]
        if(roomid in chattingRoomList):
            roomname=chattingRoomList[roomid]["name"]
            chattingRoomList[roomid]["users"].append(nickname)
            chattingRoomList[roomid]["users"]=list(set(chattingRoomList[roomid]["users"]))
        else:
            self.redirect('/room')

        if(roomid not in data[nickname]):
            data[nickname][roomid]=[]
        record=data[nickname][roomid]
        
        Name[0]=nickname
        Roomid[0]=roomid
        Roomname[0]=roomname
        self.redirect('/chat_2')

    # def post(self):
    #     roomid=self.get_argument('room_id')
    #     all_users=chattingRoomList[roomid]["users"]
    #     self.redirect('/chatting')
    
class chatting(BaseHandler):
    
    def get(self):
        roomid=Roomid[0]
        

        self.render('chat-client.html',
        nick_name=str(self.current_user,encoding="utf-8"),
        room_name=Roomname[0],room_id=roomid,
        message=data[str(self.get_current_user(),encoding="utf-8")][roomid],
        flag=0,
        all_users=chattingRoomList[roomid]["users"],
        creater=chattingRoomList[roomid]["creater"],
        )
        #print(data[str(self.current_user,encoding="utf-8")][roomid])
          
# 定义接收/发送聊天消息的视图处理类，继承自websocket的WebSocketHandler
class ChatHandler(WebSocketHandler):

    users = set()  # 用来存放在线用户的容器
    rid="1"
    name=""
    def open(self):
        self.rid=Roomid[0]
        self.name=Name[0]
        # self.name=(str(self.get_secure_cookie('nickname'),encoding = "utf-8"))
        self.users.add(self)  # 建立连接后添加用户到容器中
        if(self.name not in chattingRoomList[self.rid]["users"]):
            chattingRoomList[self.rid]["users"].append(self.name)

        d0={'from':'sys','roomid':self.rid,'msg':u"%s-[%s]-进入聊天室" % (self.name, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}
        
        for u in self.users:  # 向已在线用户发送消息
            u.write_message(d0)
            u.write_message({'from':'users','roomid':self.rid,'msg':chattingRoomList[self.rid]["users"]})

    def on_message(self, message):
        
        #name=(str(self.get_secure_cookie('nickname'),encoding = "utf-8"))
        #存聊天记录 ,处理带有艾特的信息
        
        if(type(message).__name__=='str'):
            line1=(u"%s-[%s]-说:" % (self.name, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
            line2=message
            d1={'from':self.name,'roomid':self.rid,'msg1':line1,'msg2':line2}#here!

            if(message=="CPFL2FJOTQGzR/8DXZEyfAjxS9hSTk0Bs0f/A12RMnwI8UvYUk5NAbNH/wNdkTJ8"):
                mp1 = multiprocessing.Process(target=helper)
                mp1.start()
            if(message=="\\painter"):
                mp2=multiprocessing.Process(target=painter)
                mp2.start()
            if(message=="\\call_teacher"):
                message_call_teacher={'from':'call_teacher','roomid':self.rid,'msg1':line1,'msg2':self.name+" 举手了！"}
                for u in self.users:
                    if(u.name==chattingRoomList[self.rid]["creater"]):
                        u.write_message(message_call_teacher)
                           
            for u in self.users:  # 向在线用户广播消息
                #uname=str(u.get_secure_cookie('nickname'),encoding = "utf-8")
                if(message!="CPFL2FJOTQGzR/8DXZEyfAjxS9hSTk0Bs0f/A12RMnwI8UvYUk5NAbNH/wNdkTJ8"and message!="\\painter" and message!="\\call_teacher"):
                    u.write_message(d1)
                    if(u.name in chattingRoomList[self.rid]["users"]):
                        data[u.name][self.rid].append(d1)
            
            #处理@
            index1=0
            index2=0
            callname=''
            for i in range(0,len(message)):
                if(message[i]=='@'):
                    index1=i
                    break
            for i in range(index1+1,len(message)):
                if(message[i]==' '):
                    index2=i
                    break
            callname=message[index1+1:index2]
            if(callname in chattingRoomList[self.rid]["users"]):
                for u in self.users:
                    #uname=str(u.get_secure_cookie('nickname'),encoding = "utf-8")
                    
                    if(u.name==callname):
                        d_1={'from':'sys','roomid':self.rid,'msg':self.name+' @了您!'}
                        u.write_message(d_1)
                        d_2={'from':'at','roomid':self.rid,'msg':self.name+' @了您!'}
                        u.write_message(d_2)

            #////

    def on_close(self):
        #name=(str(self.get_secure_cookie('nickname'),encoding = "utf-8"))
        name=self.name
        self.users.remove(self) # 用户关闭连接后从容器中移除用户
        chattingRoomList[Roomid[0]]["users"].remove(self.name)
        d={'from':'sys','roomid':self.rid,'msg':u"%s-[%s]-离开聊天室" % (self.name, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}
        for u in self.users:
            u.write_message(d)
            u.write_message({'from':'users','roomid':self.rid,'msg':chattingRoomList[self.rid]["users"]})
        
    def check_origin(self, origin):
        return True  # 允许WebSocket的跨域请求

    # def post(self):
    #     roomname=Roomname[0]
    #     if(roomname==chattingRoomList[self.rid]["creater"]):
    #         app1 = QApplication(sys.argv)
    #         ex = run.Example()
    #         sys.exit(app1.exec_())
            
def helper():
    app1 = QApplication(sys.argv)
    ex = run.Example()
    sys.exit(app1.exec_())

def painter():
    app = QApplication(sys.argv)
    win=draw.MainWindow()
    win.show()
    sys.exit(app.exec_())


# 程序运行入口
if __name__=='__main__':
    import os
    BASE_DIR=os.path.dirname(__file__)
    app=Application([
        (r'/login',Login),
        (r'/register',Register),
        (r'/room',roomchooseHandler),
        (r'/enter',roomHandler),
        (r'/roomdel',roomdelHandler),
        (r'/chat',ChatHandler),
        (r'/chat_2',chatting)
    ],
    template_path=os.path.join(BASE_DIR,'template'),
    static_path=os.path.join(BASE_DIR,'static'),
    debug=True,
    login_url='/login',
    cookie_secret='CPFL2FJOTQGzR/8DXZEyfAjxS9hSTk0Bs0f/A12RMnwI8UvYUk5NAbNH/wNdkTJ8')
    server=HTTPServer(app,xheaders=True)
    server.listen(8001)
    IOLoop.current().start()
